import redis
from utils.config import load_config


def connect_to_redis():
    """连接 Redis 数据库"""
    config = load_config()
    try:
        # 创建 Redis 连接
        client = redis.Redis(
            host=config['redis']['host'],
            port=config['redis']['port'],
            password=config['redis']['password'],
            db=0,
            decode_responses=True  # 将返回的字节数据解码为字符串
        )
        # 测试连接
        client.ping()
        print("连接 Redis 成功")
        return client
    except Exception as e:
        print(f"连接 Redis 时发生错误: {e}")
        return None


def basic_operations(client):
    """Redis 基本操作"""
    if client is None:
        print("Redis 客户端未初始化")
        return

    # 设置键值对
    client.set('name', 'Alice')
    print("设置键值对: name -> Alice")

    # 获取键值对
    name = client.get('name')
    print(f"获取键值对: name -> {name}")

    # 删除键
    client.delete('name')
    print("删除键: name")

    # 检查键是否存在
    exists = client.exists('name')
    print(f"键 'name' 是否存在: {exists}")
